package kryptologieBlatt1;


public class LetterFrequency {

	private String alphabet;
	private String chiffre;
	private int[] countedFrequency;
	private LetterPair[] sortedFrequency;
	
	
	public LetterFrequency(String chiffre) {
		initVariables(chiffre);
	}
	
	private void countAndSortLetters(){
		countFrequency();
		sortCountedFrequency();
	}
	
	public LetterPair[] getSortedFrequency() {
		countAndSortLetters();
		return sortedFrequency;
	}
	
	private void initVariables(String chiffre) {
		this.alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		this.chiffre = chiffre;
		this.countedFrequency = new int[26];
		this.sortedFrequency = new LetterPair[26];
	}

	private char getLetterFromIndex(int index){
		return alphabet.charAt(index);
	}
	
	private void countFrequency() {
		int length = chiffre.length();
		for (int i = 0; i < length; i++) {
			countedFrequency[getLetterIndex(chiffre.charAt(i) + "")]++;
		}
	}
	
	private int getLetterIndex(String letter){
		return letter.charAt(0) - 'A';
	}
	
	private void sortCountedFrequency(){
		int[] freq = countedFrequency.clone();
		int length = freq.length;
		LetterPair[] acc = new LetterPair[length];
		LetterPair pair;
		int index = 0;
		int max = -1;
		int val = -1;
		for (int j = 0; j < length; j++) {
			for (int i = 0; i < length; i++) {
				val = freq[i];
				if(val > max){
					max = val;
					index = i;
				}
			}
			pair = new LetterPair(getLetterFromIndex(index) + "", max);
			acc[j] = pair;
			freq[index] = -1;
			max = -1;
		}
		sortedFrequency = acc;
	}
		
}
